#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
单个项目重命名对话框
"""

import tkinter as tk
from tkinter import ttk, messagebox
import ttkbootstrap as ttk_bs
from ttkbootstrap.constants import *


class SingleProjectRenameDialog:
    """单个项目重命名对话框"""
    
    def __init__(self, parent, project_info):
        self.parent = parent
        self.project_info = project_info
        self.result = None
        self.dialog = None
        self.create_dialog()
    
    def create_dialog(self):
        """创建对话框"""
        self.dialog = tk.Toplevel(self.parent)
        self.dialog.title(f"修改项目名称 - {self.project_info['name']}")
        self.dialog.geometry("500x300")
        self.dialog.resizable(False, False)
        self.dialog.grab_set()
        
        # 主框架
        main_frame = ttk.Frame(self.dialog, padding=20)
        main_frame.pack(fill=BOTH, expand=True)
        
        # 项目信息显示
        info_frame = ttk.LabelFrame(main_frame, text="项目信息", padding=10)
        info_frame.pack(fill=X, pady=(0, 15))
        
        ttk.Label(info_frame, text="原始名称:", font=("等线", 9, "bold")).pack(anchor=W)
        ttk.Label(info_frame, text=self.project_info['name'], foreground="gray").pack(anchor=W, pady=(0, 5))
        
        ttk.Label(info_frame, text="项目路径:", font=("等线", 9, "bold")).pack(anchor=W)
        ttk.Label(info_frame, text=self.project_info['path'], font=("等线", 8), foreground="gray").pack(anchor=W)
        
        # 当前智能名称（如果有）
        if 'smart_name' in self.project_info:
            ttk.Label(info_frame, text="当前智能名称:", font=("等线", 9, "bold")).pack(anchor=W, pady=(10, 0))
            ttk.Label(info_frame, text=self.project_info['smart_name'], foreground="green").pack(anchor=W, pady=(0, 5))
            default_name = self.project_info['smart_name']
        else:
            # 使用翻译器生成默认名称
            from utils.name_translator import name_translator
            default_name = name_translator.suggest_name(self.project_info['name'])
        
        # 新仓库名称输入
        input_frame = ttk.LabelFrame(main_frame, text="新仓库名称", padding=10)
        input_frame.pack(fill=X, pady=(0, 15))
        
        ttk.Label(input_frame, text="请输入新的仓库名称:", font=("等线", 9, "bold")).pack(anchor=W, pady=(0, 5))
        
        input_container = ttk.Frame(input_frame)
        input_container.pack(fill=X)
        
        self.name_var = tk.StringVar(value=default_name)
        self.name_entry = ttk.Entry(input_container, textvariable=self.name_var, font=("等线", 10))
        self.name_entry.pack(side=LEFT, fill=X, expand=True, padx=(0, 8))
        
        # 智能生成按钮
        smart_btn = ttk_bs.Button(
            input_container,
            text="🤖",
            bootstyle=SUCCESS,
            width=4,
            command=self.generate_smart_name
        )
        smart_btn.pack(side=RIGHT)
        
        # 提示信息
        ttk.Label(input_frame, 
                 text="仓库名称需符合Git规范：小写字母、数字、下划线、中划线",
                 font=("等线", 8),
                 foreground="gray").pack(anchor=W, pady=(5, 0))
        
        # 按钮框架
        button_frame = ttk.Frame(main_frame)
        button_frame.pack(fill=X)
        
        ttk_bs.Button(
            button_frame, 
            text="确定", 
            bootstyle=SUCCESS,
            command=self.ok_clicked
        ).pack(side=LEFT, padx=(0, 10))
        
        ttk_bs.Button(
            button_frame, 
            text="取消", 
            bootstyle=SECONDARY,
            command=self.cancel_clicked
        ).pack(side=LEFT)
        
        # 居中显示
        self.dialog.transient(self.parent)
        self.dialog.wait_window()
    
    def generate_smart_name(self):
        """生成智能名称"""
        try:
            from core.deepseek_ai import DeepSeekAI
            from core.config import config_manager
            
            api_key = config_manager.get('ai.deepseek_api_key', '')
            if not api_key:
                messagebox.showerror("错误", "请先配置DeepSeek API Key")
                return
            
            deepseek = DeepSeekAI(api_key)
            smart_name = deepseek.generate_repository_name(
                self.project_info['name'], 
                self.project_info['path']
            )
            self.name_var.set(smart_name)
            
        except Exception as e:
            messagebox.showerror("错误", f"生成智能名称失败: {str(e)}")
    
    def ok_clicked(self):
        """确定按钮点击"""
        import re
        
        new_name = self.name_var.get().strip()
        
        if not new_name:
            messagebox.showerror("错误", "仓库名称不能为空")
            return
        
        # 验证名称格式
        if not re.match(r'^[a-zA-Z0-9_-]+$', new_name):
            messagebox.showerror("错误", "仓库名称格式不正确，只能包含字母、数字、下划线和中划线")
            return
        
        if len(new_name) > 100:  # Gitee限制
            messagebox.showerror("错误", "仓库名称过长，请控制在100字符以内")
            return
        
        self.result = new_name
        self.dialog.destroy()
    
    def cancel_clicked(self):
        """取消按钮点击"""
        self.dialog.destroy()
